package com.tairanchina.md.meeting.resource;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
import com.tairanchina.md.elife.rabbit.client.consumer.RabbitConsumerClient;
import com.tairanchina.md.elife.rabbit.client.consumer.impl.TXConsumerRabbitClient;
import com.tairanchina.md.elife.rabbit.constants.ConnConstants;
import com.tairanchina.md.elife.rabbit.task.RabbitMQTask;
import com.tairanchina.md.meeting.constants.MeetingConstants;
import com.tairanchina.md.meeting.constants.MeetingProvider;
import com.tairanchina.md.meeting.dto.UserAwarderDto;
import com.tairanchina.md.meeting.dto.UserSignDto;
import com.tairanchina.md.meeting.entity.YearMeetingSunawarder;
import com.tairanchina.md.meeting.entity.YearMeetingUser;
import com.tairanchina.md.turntable.dto.YearMeetingSunawarderDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeoutException;

/**
 * 向页面推送中奖信息
 */

@ServerEndpoint("/sun/awarder")
public class PushSunAwarderWS implements RabbitMQTask,Runnable
{
    Logger logger = LoggerFactory.getLogger(PushSunAwarderWS.class);


    private Session session;

    private static Set<PushSunAwarderWS> awarderWSes = new HashSet();

    @OnMessage
    public void onMessage(String message, Session session) throws IOException, InterruptedException
    {

    }

    @Override
    public void consumerMsg(Object obj,Object... objs) throws Exception
    {


        //如果浏览器关闭，则不消费消息

        YearMeetingSunawarderDto awarderMsg = (YearMeetingSunawarderDto)obj ;


        //查询中奖用户的实名信息
        YearMeetingUser user = MeetingProvider.userService.findUserByPhone(awarderMsg.getUserPhone());

        if(user != null){

            awarderMsg.setDepartment(user.getDepartment());
            awarderMsg.setUserName(user.getUserName());

            //保存用户的中奖信息,同时更新奖品数量
            MeetingProvider.sunAwarderService.addAwarderAndUpdateSunGood(awarderMsg,user);

            //进行弹幕
            for(PushSunAwarderWS awarderWS :awarderWSes){
                sentText(awarderMsg,awarderWS.session,user);
            }

        }




    }

    //发送弹幕
    private void sentText(YearMeetingSunawarderDto awarderMsg,Session session,YearMeetingUser user){

        //发送弹幕
        try {

            //如果用户的中奖金额大于50就进行弹幕
            if (awarderMsg.getAwardMoney() >= 50) {

                //发送弹幕
                UserAwarderDto awarderDto = new UserAwarderDto();
                awarderDto.setDepartment(awarderMsg.getDepartment());
                awarderDto.setUserName(awarderMsg.getUserName());
                awarderDto.setUserPhone(awarderMsg.getUserPhone());
                awarderDto.setAwardMoney(awarderMsg.getAwardMoney());
                awarderDto.setCompany(user.getCompany());
                awarderDto.setUserPic(user.getUserPic());
                session.getBasicRemote().sendText(JSON.toJSONString(awarderDto));


             }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发送弹幕失败,e:{}",e);
        }
    }
    @OnOpen
    public void onOpen(Session session)
    {
        System.out.println("客户端已连接------------");
        this.session = session;
        awarderWSes.add(this);
    }

    @OnClose
    public void onClose()
    {
        System.out.println("客户端连接断开------------");
        awarderWSes.remove(this);
    }

    @OnError
    public void onError(Session session, Throwable error)
    {
        System.out.println("Connection error" + error);

    }

    @Override
    public void run() {
        RabbitConsumerClient consumerClient = ConnConstants.getConsumerClient();
        //处理接收消息
        while (true)
        {
            try {
                consumerClient.receiveMessage(MeetingConstants.QUEUE_NAME_SUN_LOCAL, this);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("用户摇奖消息消费失败,e:{}",e);
            }
        }
    }
}
